// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LiveObjectContainerCache.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework.LiveObjects
{
    #region Usings

    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;

    using Org.OpenTrader.Framework.DataModel;
    using Org.OpenTrader.Framework.Enums;
    using Org.OpenTrader.Framework.LiveObjects.Interfaces;

    #endregion

    /// <summary>
    /// The live object container cache.
    /// </summary>
    public class LiveObjectContainerCache : IDisposable
    {
        #region Constants and Fields

        /// <summary>
        /// The containersUptodate.
        /// </summary>
        private readonly IDictionary<Guid, bool> containersUptodate = new Dictionary<Guid, bool>();

        /// <summary>
        /// The dbExecutionContext.
        /// </summary>
        private readonly DBExecutionContext dbExecutionContext;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="LiveObjectContainerCache"/> class.
        /// </summary>
        /// <param name="dbCtx">
        /// The dbCtx.
        /// </param>
        public LiveObjectContainerCache(DBExecutionContext dbCtx)
        {
            this.dbExecutionContext = dbCtx;

            dbCtx.DBContainer.Load();
            foreach (var dbContainer in dbCtx.DBContainer)
            {
                this.containersUptodate[dbContainer.ID] = false;
            }
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets Containers.
        /// </summary>
        public ILiveObjectContainer[] Containers
        {
            get
            {
                IList<ILiveObjectContainer> containers = new List<ILiveObjectContainer>();
                var containersIds = this.containersUptodate.Keys.ToArray();
                foreach (var containerId in containersIds)
                {
                    containers.Add(this.GetContainer(containerId));
                }

                return containers.ToArray();
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The container added.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        public void ContainerAdded(Guid id)
        {
            this.containersUptodate[id] = false;
        }

        /// <summary>
        /// The container deleted.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        public void ContainerDeleted(Guid id)
        {
            if (this.containersUptodate.ContainsKey(id))
            {
                this.containersUptodate.Remove(id);
                Singleton<LiveObjectsRegistry>.Instance.DestroyContainer(id);
            }
        }

        /// <summary>
        /// The container upgraded.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        public void ContainerUpgraded(Guid id)
        {
            this.containersUptodate[id] = false;
        }

        /// <summary>
        /// The get container.
        /// </summary>
        /// <param name="id">
        /// The id.
        /// </param>
        /// <returns>
        /// </returns>
        public ILiveObjectContainer GetContainer(Guid id)
        {
            // Not known
            if (!this.containersUptodate.ContainsKey(id))
            {
                return null;
            }

            // Not up to date (resources added/removed, container created, etc ...)
            if (this.containersUptodate[id] == false)
            {
                // Already exists. Delete it !
                if (Singleton<LiveObjectsRegistry>.Instance.ExistsContainer(id))
                {
                    Singleton<LiveObjectsRegistry>.Instance.DestroyContainer(id);
                }

                // Fresh new
                this.dbExecutionContext.DBContainer.Load();
                var dbContainers = from c in this.dbExecutionContext.DBContainer where c.ID == id select c;

                if (dbContainers.Count() == 1)
                {
                    var dbContainer = dbContainers.First();

                    var resources = DBContainerHelpers.GetResources(dbContainer.ID);

                    var dir = string.Format(
                        "{0}\\OTAdmUI\\{1}\\{2}", Path.GetTempPath(), Process.GetCurrentProcess().Id, dbContainer.ID);

                    ILiveObjectContainerDescriptor desc =
                        new LiveObjectContainerDescriptor(
                            ELiveObjectContainerType.AppDomainIsolationContainer, 
                            dbContainer.ID, 
                            dbContainer.Name, 
                            dir, 
                            resources, 
                            Singleton<LiveObjectsRegistry>.Instance);

                    // Create the container
                    this.containersUptodate[id] = Singleton<LiveObjectsRegistry>.Instance.CreateContainer(desc);
                }
            }

            // The uptodate container
            return Singleton<LiveObjectsRegistry>.Instance.GetContainer(id);
        }

        #endregion

        #region Implemented Interfaces

        #region IDisposable

        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            foreach (var containerId in Singleton<LiveObjectsRegistry>.Instance.Containers)
            {
                Singleton<LiveObjectsRegistry>.Instance.DestroyContainer(containerId);
            }

            this.containersUptodate.Clear();
        }

        #endregion

        #endregion
    }
}